﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using My.GenCode.Entities;
using My.GenCode.Interface;

namespace My.GenCode.Templates
{
    public class GenEntityClass : CodeTemplate
    {
        #region 覆盖父类的方法

        public GenEntityClass(string tpl, EntityInfo info,string desc) : base(tpl, info,desc) { }

        protected override string ProcTemplate()
        {
            _tpl = this.LoopProperties(_tpl, "<PropertiesCodeBlock>", this.GenProperty);  // 处理[loop<PropertiesCodeBlock>][/loop]标签
            _tpl = this.LoopProperties(_tpl, "<IEnumeratorField>", this.GenIEnumeratorField);

            _tpl = _tpl.Replace("<FileName>", _nh.EntityClassFileName);            // 处理<FileName>标签
            _tpl = _tpl.Replace("<NameSpace>", _nh.NameSpace);                     // 处理<NameSpace>标签
            _tpl = _tpl.Replace("<ClassName>", _nh.EntityClassName);               // 处理<ClassName>标签
            _tpl = _tpl.Replace("<EntityName>", _nh.EntityName);                   // 处理<EntityName>标签
            _tpl = _tpl.Replace("<EqualsCondition>", EqualsCondition);             // 处理<EqualsCondition>标签

            return _tpl;
        }

        protected override string OutputFilename()
        {
            return @"Domain\Entities\" + _nh.EntityClassFileName;
        }

        #endregion

        #region 处理循环标签的方法

        /// <summary>
        /// 替换属性标签模板
        /// </summary>
        /// <param name="tpl"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        private string GenProperty(string tpl,PropertyInfo info)
        {
            tpl = tpl.Replace("<Type>", info.Type);
            tpl = tpl.Replace("<Name>", info.Name);
            return tpl;
        }

        /// <summary>
        /// IEnumerator属性模板
        /// </summary>
        private string GenIEnumeratorField(string tpl, PropertyInfo info)
        {
            tpl = tpl.Replace("<Name>", info.Name);
            return tpl;
        }

        /// <summary>
        /// 相等条件
        /// </summary>
        private string EqualsCondition
        {
            get 
            {
                List<string> list = new List<string>();
                foreach (PropertyInfo p in _info.Properties)
                {
                    list.Add(string.Format("this.{0}.Equals(info.{0})", p.Name));
                }
                return string.Join("\r\n             && ", list.ToArray());
            }
        }

        #endregion
    }
}